const app = getApp()
Page({
  data: {
    expand: false,
    showTypeSelector: false,
    currentType: 0,
    currentTypeName: '',
    maxDate: new Date().getTime(),
    minDate: new Date(2010, 1, 1).getTime(),
    currentDate: new Date().getTime(),
    currentDateText: '',
    projectInfo: {},
    deviceList: [],
    customerList: [],
    projectList: [],
    userList: [],
    projectID: '',
    type: 'add',
    title: '添加项目'
  },

  onLoad(option) {
    if (option.id) {
      this.setData({
        projectID: option.id,
        type: 'edit',
        title: '编辑项目'
      })
    }
    // 初始化数据加载
    Promise.all([
      this.getCustomerList(),
      this.getProjectList(),
      this.getUserList(),
      option.id ? this.getDeviceList(option.id) : Promise.resolve()
    ]).then(() => {
      if (option.id) this.getProjectInfo(option.id)
    })
  },

  // 获取客户列表
  getCustomerList() {
    return new Promise(resolve => {
      app.axios('customer', { op: 'ajaxCustomerList' }).then(res => {
        if (res.code) {
          this.setData({ customerList: res.lists }, resolve)
        }
      })
    })
  },

  // 获取项目列表
  getProjectList() {
    return new Promise(resolve => {
      app.axios('item', { op: 'ajaxItemList' }).then(res => {
        if (res.code) {
          this.setData({ projectList: res.lists }, resolve)
        }
      })
    })
  },

  // 获取用户列表
  getUserList() {
    return new Promise(resolve => {
      app.axios('user', { op: 'ajaxUserDlList' }).then(res => {
        if (res.code) {
          this.setData({ userList: res.lists }, resolve)
        }
      })
    })
  },

  // 获取设备列表
  getDeviceList(id) {
    return new Promise(resolve => {
      app.axios('device', { op: 'ajaxGbdcAll' }).then(res => {
        if (res.code) {
          this.setData({ deviceList: res.lists }, resolve)
        }
      })
    })
  },

  // 获取项目详情
  getProjectInfo(id) {
    app.axios('item', { op: 'ajaxItemDetail', id }).then(res => {
      if (res.code) {
        this.processProjectData(res.item)
      }
    })
  },

  // 处理项目数据回填
  processProjectData(item) {
    // 原有回填逻辑保持不变
    const customerList = this.data.customerList.map(c => ({
      ...c,
      selected: c.id === item.customerid
    }))

    const selectedUserIds = item.userid ? item.userid.split(',') : []
    const userList = this.data.userList.map(u => ({
      ...u,
      selected: selectedUserIds.includes(u.id.toString())
    }))

    const projectList = this.data.projectList.map(p => ({
      ...p,
      selected: p.id === item.pid
    }))

    const selectedDeviceIds = item.dids || []
    const deviceList = this.data.deviceList.map(d => ({
      ...d,
      selected: selectedDeviceIds.includes(d.id.toString())
    }))

    // 新增设备对象匹配逻辑
    const matchedDevices = this.data.deviceList.filter(d =>
      selectedDeviceIds.includes(d.id.toString())
    )

    this.setData({
      projectInfo: {
        ...item,  // 保留原始数据
        deviceList: matchedDevices  // 添加匹配的设备对象
      },
      customerList,
      userList,
      projectList,
      deviceList
    })
  },

  // 以下保持原有方法结构
  toggleCustomerPicker() {
    this.selectComponent('#picker-customer').togglePicker()
  },

  toggleUserPicker() {
    this.selectComponent('#picker-user').togglePicker()
  },

  toggleProjectPicker() {
    this.selectComponent('#picker-project').togglePicker()
  },

  toggleDevicePicker() {
    this.selectComponent('#picker-device').togglePicker()
  },

  handleCustomerConfirm(e) {
    const selected = e.detail.selectedItems[0]
    if (selected) {
      this.setData({
        'projectInfo.customerName': selected.name,
        'projectInfo.customerid': selected.id,
        'customerList': this.data.customerList.map(c => ({
          ...c,
          selected: c.id === selected.id
        }))
      })
    }
  },

  handleUserConfirm(e) {
    const selected = e.detail.selectedItems
    if (selected.length > 0) {
      const names = selected.map(u => u.name).join(',')
      const ids = selected.map(u => u.id)
      this.setData({
        'projectInfo.parters': names,
        'projectInfo.userid': ids.join(','),
        'userList': this.data.userList.map(u => ({
          ...u,
          selected: ids.includes(u.id)
        }))
      })
    }
  },

  handleProjectConfirm(e) {
    const selected = e.detail.selectedItems[0]
    if (selected) {
      this.setData({
        'projectInfo.pname': selected.name,
        'projectInfo.pid': selected.id,
        'projectList': this.data.projectList.map(p => ({
          ...p,
          selected: p.id === selected.id
        }))
      })
    }
  },

  handleDeviceConfirm(e) {
    const selected = e.detail.selectedItems
    const deviceList = this.data.deviceList.map(d => ({
      ...d,
      selected: selected.some(s => s.id === d.id)
    }))
    this.setData({
      'projectInfo.deviceList': selected,
      'projectInfo.dids': selected.map(d => d.id).toString(),
      deviceList
    })
  },
  handleInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [`projectInfo.${field}`]: e.detail.value
    })
  },
  removeDeviceById(e) {
    const id = e.currentTarget.dataset.id.toString()// 确保id是字符串
    const projectInfo = this.data.projectInfo

    // 更新projectInfo中的deviceList和dids
    const newDeviceList = projectInfo.deviceList.filter(device =>
      device.id.toString() !== id
    );
    const newDids = newDeviceList.map(device => device.id).join(',')

    // 更新页面data中的deviceList的selected状态
    const deviceList = this.data.deviceList.map(device => {
      if (device.id.toString() === id) {
        return { ...device, selected: false };
      }
      return device
    })

    this.setData({
      'projectInfo.deviceList': newDeviceList,
      'projectInfo.dids': newDids,
      deviceList: deviceList
    })
  },
  navigateTo(e) {
    app.navigateTo(e.currentTarget.dataset.url, e.currentTarget.dataset.type)
  },

  toggleExpand() {
    this.setData({ expand: !this.data.expand })
  },
  toggleMapMarker() {
    const mapMarker = this.selectComponent('#v-map')
    mapMarker.toggleMapMarker()
  },
  comitMapResult(res) {
    this.setData({
      'projectInfo.addr': res.detail.selectedAddress,
      'projectInfo.ilat': res.detail.userLocation.latitude,
      'projectInfo.ilng': res.detail.userLocation.longitude,
    })
  },
  comfirm() {
    const params = this.data.projectInfo
    let op = 'ajaxItemAdd'
    let title = '添加成功'
    if (this.data.type === 'edit') {
      op = 'ajaxItemUp'
      title = '编辑成功'
    }
    if (params.dids) {
      params.dids = Array.isArray(params.dids) ?
        params.dids.join(',') :
        String(params.dids)
    } else {
      params.dids = '' // 处理空值情况
    }
    params.op = op
    const { deviceList, ...newParams } = params;
    console.log(newParams, 'params')
    app.axios('item', newParams).then(res => {
      if (res.code) {
        wx.showToast({
          title: title,
          icon: 'success'
        })
        setTimeout(() => {
          app.navigateTo('/pages/operation-center/index/index?activeTab=4', 'redirectTo')
        }, 1500);
      }
    })
  }
})